<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑试题' : '添加试题' }}</span>
      </div>
      
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="题目内容" prop="content">
          <el-input type="textarea" v-model="form.content" placeholder="请输入题目内容" :rows="4"></el-input>
        </el-form-item>
        
        <el-form-item label="题目类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择题目类型" @change="handleTypeChange" style="width: 100%">
            <el-option label="单选题" :value="1"></el-option>
            <el-option label="多选题" :value="2"></el-option>
            <el-option label="判断题" :value="3"></el-option>
            <el-option label="填空题" :value="4"></el-option>
            <el-option label="简答题" :value="5"></el-option>
          </el-select>
        </el-form-item>
        
        <!-- 选项（单选题和多选题） -->
        <template v-if="form.type === 1 || form.type === 2">
          <el-form-item
            v-for="(option, index) in options"
            :key="index"
            :label="'选项' + optionLabels[index]"
            :prop="'options.' + index + '.content'"
            :rules="{
              required: true, message: '选项内容不能为空', trigger: 'blur'
            }"
          >
            <div class="option-input">
              <el-input v-model="option.content" placeholder="请输入选项内容"></el-input>
              <el-button type="danger" icon="el-icon-delete" circle size="mini" @click.prevent="removeOption(index)" v-if="options.length > 2"></el-button>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" plain size="small" icon="el-icon-plus" @click="addOption">添加选项</el-button>
          </el-form-item>
          
          <el-form-item label="正确答案" prop="answer">
            <el-checkbox-group v-model="selectedOptions" v-if="form.type === 2">
              <el-checkbox v-for="(label, index) in optionLabels.slice(0, options.length)" :key="index" :label="label">{{ label }}</el-checkbox>
            </el-checkbox-group>
            <el-radio-group v-model="selectedOption" v-else>
              <el-radio v-for="(label, index) in optionLabels.slice(0, options.length)" :key="index" :label="label">{{ label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
        
        <!-- 判断题 -->
        <el-form-item label="正确答案" prop="answer" v-if="form.type === 3">
          <el-radio-group v-model="form.answer">
            <el-radio label="true">正确</el-radio>
            <el-radio label="false">错误</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 填空题 -->
        <template v-if="form.type === 4">
          <el-form-item
            v-for="(blank, index) in blanks"
            :key="index"
            :label="'空' + (index + 1)"
            :prop="'blanks.' + index + '.answer'"
            :rules="{
              required: true, message: '答案不能为空', trigger: 'blur'
            }"
          >
            <div class="blank-input">
              <el-input v-model="blank.answer" placeholder="请输入答案"></el-input>
              <el-button type="danger" icon="el-icon-delete" circle size="mini" @click.prevent="removeBlank(index)" v-if="blanks.length > 1"></el-button>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" plain size="small" icon="el-icon-plus" @click="addBlank">添加空格</el-button>
          </el-form-item>
        </template>
        
        <!-- 简答题 -->
        <el-form-item label="参考答案" prop="answer" v-if="form.type === 5">
          <el-input type="textarea" v-model="form.answer" placeholder="请输入参考答案" :rows="4"></el-input>
        </el-form-item>
        
        <el-form-item label="答案解析" prop="analysis">
          <el-input type="textarea" v-model="form.analysis" placeholder="请输入答案解析" :rows="3"></el-input>
        </el-form-item>
        
        <el-form-item label="难度" prop="difficulty">
          <el-select v-model="form.difficulty" placeholder="请选择难度" style="width: 100%">
            <el-option label="简单" :value="1"></el-option>
            <el-option label="中等" :value="2"></el-option>
            <el-option label="困难" :value="3"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="教育阶段" prop="educationLevel">
          <el-select v-model="form.educationLevel" placeholder="请选择教育阶段" @change="handleEducationLevelChange" style="width: 100%">
            <el-option label="小学" :value="1"></el-option>
            <el-option label="初中" :value="2"></el-option>
            <el-option label="高中" :value="3"></el-option>
            <el-option label="大学" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择学科" filterable style="width: 100%">
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getQuestionDetail, addQuestion, updateQuestion } from '@/api/question';
import { getAllSubjects } from '@/api/subject';

export default {
  name: 'QuestionEdit',
  data() {
    return {
      isEdit: false,
      questionId: null,
      form: {
        content: '',
        type: undefined,
        options: '',
        answer: '',
        analysis: '',
        difficulty: undefined,
        educationLevel: undefined,
        subjectId: undefined
      },
      options: [
        { key: 'A', content: '' },
        { key: 'B', content: '' },
        { key: 'C', content: '' },
        { key: 'D', content: '' }
      ],
      optionLabels: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
      selectedOption: '',
      selectedOptions: [],
      blanks: [{ answer: '' }],
      rules: {
        content: [
          { required: true, message: '请输入题目内容', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择题目类型', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请输入答案', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        educationLevel: [
          { required: true, message: '请选择教育阶段', trigger: 'change' }
        ],
        subjectId: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ]
      },
      subjectOptions: [],
      allSubjects: []
    };
  },
  watch: {
    selectedOption(val) {
      if (this.form.type === 1 && val) {
        this.form.answer = val;
      }
    },
    selectedOptions(val) {
      if (this.form.type === 2 && val) {
        this.form.answer = val.join(',');
      }
    }
  },
  created() {
    this.questionId = this.$route.params.id;
    this.isEdit = !!this.questionId;
    
    this.getSubjects();
    
    if (this.isEdit) {
      this.getQuestionDetail();
    }
  },
  methods: {
    // 获取学科列表
    getSubjects() {
      getAllSubjects().then(response => {
        this.allSubjects = response.data;
        this.filterSubjectsByLevel(this.form.educationLevel);
      });
    },
    // 根据教育阶段筛选学科
    filterSubjectsByLevel(level) {
      if (!level || !this.allSubjects || this.allSubjects.length === 0) {
        this.subjectOptions = this.allSubjects.map(subject => ({
          value: subject.id,
          label: subject.name
        }));
        return;
      }
      
      const filteredSubjects = this.allSubjects.filter(subject => subject.level === level);
      this.subjectOptions = filteredSubjects.map(subject => ({
        value: subject.id,
        label: subject.name
      }));
      
      // 如果当前选中的学科不在筛选结果中，清空选择
      if (this.form.subjectId) {
        const exists = filteredSubjects.some(subject => subject.id === this.form.subjectId);
        if (!exists) {
          this.form.subjectId = undefined;
        }
      }
    },
    // 教育阶段变化时触发
    handleEducationLevelChange(level) {
      this.filterSubjectsByLevel(level);
    },
    // 题目类型变化时触发
    handleTypeChange(type) {
      // 重置答案
      this.form.answer = '';
      this.selectedOption = '';
      this.selectedOptions = [];
      
      // 重置选项
      if (type === 1 || type === 2) {
        this.options = [
          { key: 'A', content: '' },
          { key: 'B', content: '' },
          { key: 'C', content: '' },
          { key: 'D', content: '' }
        ];
      } else if (type === 4) {
        this.blanks = [{ answer: '' }];
      }
    },
    // 添加选项
    addOption() {
      if (this.options.length < 10) {
        const key = this.optionLabels[this.options.length];
        this.options.push({ key, content: '' });
      } else {
        this.$message.warning('最多只能添加10个选项');
      }
    },
    // 删除选项
    removeOption(index) {
      this.options.splice(index, 1);
      
      // 更新选中的选项
      if (this.form.type === 1) {
        if (this.selectedOption === this.optionLabels[index]) {
          this.selectedOption = '';
        }
      } else if (this.form.type === 2) {
        const removedLabel = this.optionLabels[index];
        const removedIndex = this.selectedOptions.indexOf(removedLabel);
        if (removedIndex !== -1) {
          this.selectedOptions.splice(removedIndex, 1);
        }
      }
    },
    // 添加填空
    addBlank() {
      this.blanks.push({ answer: '' });
    },
    // 删除填空
    removeBlank(index) {
      this.blanks.splice(index, 1);
    },
    // 获取试题详情
    getQuestionDetail() {
      getQuestionDetail(this.questionId).then(response => {
        const questionData = response.data;
        this.form = {
          content: questionData.content,
          type: questionData.type,
          answer: questionData.answer,
          analysis: questionData.analysis,
          difficulty: questionData.difficulty,
          educationLevel: questionData.educationLevel,
          subjectId: questionData.subjectId
        };
        
        // 处理不同类型的题目
        if (questionData.type === 1 || questionData.type === 2) {
          // 处理选项
          if (questionData.options) {
            try {
              const optionsData = JSON.parse(questionData.options);
              this.options = optionsData;
            } catch (e) {
              console.error('解析选项失败', e);
            }
          }
          
          // 处理答案
          if (questionData.type === 1) {
            this.selectedOption = questionData.answer;
          } else if (questionData.type === 2) {
            this.selectedOptions = questionData.answer.split(',');
          }
        } else if (questionData.type === 4) {
          // 处理填空题
          try {
            const blanksData = JSON.parse(questionData.answer);
            this.blanks = blanksData.map(answer => ({ answer }));
          } catch (e) {
            this.blanks = [{ answer: questionData.answer }];
          }
        }
        
        // 加载学科选项
        this.filterSubjectsByLevel(questionData.educationLevel);
      });
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const formData = { ...this.form };
          
          // 处理不同类型的题目
          if (formData.type === 1 || formData.type === 2) {
            // 处理选项
            formData.options = JSON.stringify(this.options);
            
            // 处理答案
            if (formData.type === 1) {
              formData.answer = this.selectedOption;
            } else if (formData.type === 2) {
              formData.answer = this.selectedOptions.join(',');
            }
            
            // 验证是否选择了答案
            if (!formData.answer) {
              this.$message.error('请选择正确答案');
              return;
            }
          } else if (formData.type === 4) {
            // 处理填空题
            const blankAnswers = this.blanks.map(blank => blank.answer);
            formData.answer = JSON.stringify(blankAnswers);
          }
          
          if (this.isEdit) {
            formData.id = this.questionId;
            updateQuestion(formData).then(() => {
              this.$message.success('更新成功');
              this.$router.push('/questions');
            }).catch(() => {
              this.$message.error('更新失败');
            });
          } else {
            addQuestion(formData).then(() => {
              this.$message.success('添加成功');
              this.$router.push('/questions');
            }).catch(() => {
              this.$message.error('添加失败');
            });
          }
        }
      });
    },
    // 取消
    cancel() {
      this.$router.push('/questions');
    }
  }
};
</script>

<style scoped>
.option-input, .blank-input {
  display: flex;
  align-items: center;
}

.option-input .el-input, .blank-input .el-input {
  margin-right: 10px;
  width: calc(100% - 40px);
}

.unit-text {
  margin-left: 10px;
}
</style> 